﻿using Notifications.Wpf;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Xml.Linq;
using VideoTools.Commands;
using VideoTools.Extension;
using VideoTools.Util;
using VideoTools.vo;
using ComboBox = System.Windows.Controls.ComboBox;

namespace VideoTools.SubtitleView
{
    /// <summary>
    /// MargeM3U8Page.xaml 的交互逻辑
    /// </summary>
    public partial class SearchSubtitlePage : Page
    {
        private static volatile SearchSubtitlePage _instance;
        private static object _syncRoot = new object();
        public static SearchSubtitlePage Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new SearchSubtitlePage();
                        }
                    }
                }
                return _instance;
            }
        }

        public SearchSubtitlePage()
        {
            InitializeComponent();
            Loaded += SearchSubtitlePage_Loaded;
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true });
            e.Handled = true;
        }

        private void SearchSubtitlePage_Loaded(object sender, RoutedEventArgs e)
        {
            AppConfig config = AppConfig.Instance;
            if (
                config == null
                || config.EsAddress == null
                || config.EsFingerprint == null
                || config.EsUserName == null
                || config.EsPassword == null
                || config.EsAddress.Length == 0
                || config.EsFingerprint.Length == 0
                || config.EsUserName.Length == 0
                || config.EsPassword.Length == 0
            )
            {
                SearchSubtitleCommands.Instance.OpenConfigEsCommand.ExecuteIfCan();
            }
        }

        public System.Windows.Controls.ListView AllSubitemListView()
        {
            return AllSubtitleListView;
        }

        private void Video_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            VideoDesc.Visibility = Visibility.Hidden;
        }

        public byte[] DownloadImageAsStream(string imageUrl)
        {
            using (WebClient client = new WebClient())
            {
                try
                {
                    byte[] data = client.DownloadData(imageUrl);

                    if (!Utils.isJpegImage(data))
                    {
                        return Utils.AnyImageToJpegImage(data);
                    }
                    else
                    {
                        MemoryStream stream = null;
                        try
                        {
                            stream = new MemoryStream(data);
                            return stream.ToArray();
                        }
                        catch (ArgumentNullException ex)
                        {
                            throw ex;
                        }
                        catch (ArgumentException ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            stream.Close();
                        }
                    }
                }
                catch (WebException ex)
                {
                    var contentb = new NotificationContent()
                    {
                        Title = "下载视频封面失败(点击复制)",
                        Type = NotificationType.Error,
                        Message = imageUrl + "\n" + ex.Message,
                    };
                    AppManager.Instance.NotificationManager.Show(
                        contentb,
                        onClick: () =>
                        {
                            System.Windows.Clipboard.SetText(imageUrl);
                        }
                    );
                    return null;
                }
            }
        }

        private void Video_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            TextBlock text = sender as TextBlock;
            SubtitleVideoTips tips = (SubtitleVideoTips)text.Tag;
            string filePath =
                $"D:/greensoft/elasticsearch-8.4.1/images/{tips.vtype}/{tips.mtype}/{int.Parse(tips.vid) % 100}/{tips.vid}.jpg";
            if (File.Exists(filePath))
            {
                byte[] bytes = File.ReadAllBytes(filePath);
                if (!Utils.isJpegImage(bytes))
                {
                    string tempFilePath =
                        $"D:/greensoft/elasticsearch-8.4.1/images/{tips.vtype}/{tips.mtype}/{int.Parse(tips.vid) % 100}/{tips.vid}_temp.jpg";
                    bytes = Utils.AnyImageToJpegImage(bytes);
                    File.WriteAllBytes(tempFilePath, bytes);
                    File.Delete(filePath);
                    File.Move(tempFilePath, filePath);
                }
            }
            else
            {
                if (tips.image != null && tips.image.Length > 0)
                {
                    string directoryPath = System.IO.Path.GetDirectoryName(filePath);

                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    byte[] bytes = DownloadImageAsStream(tips.image);
                    if (bytes != null)
                    {
                        // 可选：保存到文件
                        File.WriteAllBytes(filePath, bytes);
                    }
                    else
                    {
                        filePath = "D:\\greensoft\\elasticsearch-8.4.1\\images\\default.jpg";
                    }
                }
            }
            BitmapImage bitmapImage = new BitmapImage(new Uri(filePath));
            ;
            VideoDescImage.Source = bitmapImage;
            VideoDescImage.Width = bitmapImage.Width;
            VideoDescImage.Height = bitmapImage.Height;
            VideoDescDesc.Text = tips.desc;
            VideoDesc.Visibility = Visibility.Visible;
        }

        private void SearchName_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                object[] objects = new object[] { GetSearchNameComboBox(), GetSearchTextBox(), GetNameComboBox(), GetVideoComboBox() };

                System.Windows.Controls.ComboBox cbxSearchName =
                    sender as System.Windows.Controls.ComboBox;
       
                SearchSubtitleCommands.Instance.AddCurrentSearchName(cbxSearchName.Text);
                //SearchNameComboBox.IsDropDownOpen = true; // 保持下拉打开
                SearchSubtitleCommands.Instance.SearchSubtitleCommand.ExecuteIfCan(objects);
                if(!string.IsNullOrEmpty(cbxSearchName.Text))
                {
                    cbxSearchName.SelectedIndex = 0;
                }
            }
        }

        private void Search_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                object[] objects = new object[] { GetSearchNameComboBox(), GetSearchTextBox(), GetNameComboBox(), GetVideoComboBox() };
                SearchSubtitleCommands.Instance.SearchSubtitleCommand.ExecuteIfCan(objects);
            }
        }


        private void Video_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                System.Windows.Controls.ComboBox cbxVideo =
                    sender as System.Windows.Controls.ComboBox;
                if (string.IsNullOrEmpty(cbxVideo.Text))
                    return;
                SearchSubtitleCommands.Instance.AddCurrentVideo(cbxVideo.Text);
                SearchSubtitleCommands.Instance.SearchVideoCommand.ExecuteIfCan();
                cbxVideo.SelectedIndex = 0;
            }
        }

        private void Name_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                System.Windows.Controls.ComboBox cbxName =
                    sender as System.Windows.Controls.ComboBox;
                if (string.IsNullOrEmpty(cbxName.Text))
                    return;
                SearchSubtitleCommands.Instance.AddCurrentName(cbxName.Text);
                SearchSubtitleCommands.Instance.SearchNameCommand.ExecuteIfCan();
                cbxName.SelectedIndex = 0;
            }
        }

        private void VideoComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object selectedItem = GetVideoComboBox().SelectedItem;
            if (selectedItem != null)
            {
                object[] objects = new object[] { GetSearchNameComboBox(),GetSearchTextBox(),GetNameComboBox(),GetVideoComboBox()};
                if (selectedItem != null)
                {
                    if (SearchSubtitleCommands.Instance.LastVideo == null)
                    {
                        SearchSubtitleCommands.Instance.LastVideo = selectedItem.ToString();
                        SearchSubtitleCommands.Instance.SearchVideoCommand.ExecuteIfCan(objects);
                    }
                    else
                    {
                        if (!SearchSubtitleCommands.Instance.LastVideo.Equals(selectedItem.ToString()))
                        {
                            SearchSubtitleCommands.Instance.LastVideo = selectedItem.ToString();
                            SearchSubtitleCommands.Instance.SearchVideoCommand.ExecuteIfCan(objects);
                        }
                    }
                    GetVideoComboBox().SelectedIndex = 0;

                }
            }
        }

        private void NameComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object selectedItem = GetNameComboBox().SelectedItem;
            if (selectedItem != null)
            {
                object[] objects = new object[] { GetSearchNameComboBox(), GetSearchTextBox(), GetNameComboBox(), GetVideoComboBox() };

                if (SearchSubtitleCommands.Instance.LastName == null)
                {
                    SearchSubtitleCommands.Instance.LastName = selectedItem.ToString();
                    SearchSubtitleCommands.Instance.SearchNameCommand.ExecuteIfCan(objects);
                }
                else
                {
                    if (!SearchSubtitleCommands.Instance.LastName.Equals(selectedItem.ToString()))
                    {
                        SearchSubtitleCommands.Instance.LastName = selectedItem.ToString();
                        SearchSubtitleCommands.Instance.SearchNameCommand.ExecuteIfCan(objects);
                    }
                }
                GetNameComboBox().SelectedIndex = 0;
            }
        }

        private void SearchNameComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object selectedItem = GetSearchNameComboBox().SelectedItem;
            if (selectedItem != null)
            {
                object[] objects = new object[] { GetSearchNameComboBox(), GetSearchTextBox(), GetNameComboBox(), GetVideoComboBox() };

                if (SearchSubtitleCommands.Instance.LastSearchName == null)
                {
                    SearchSubtitleCommands.Instance.LastSearchName = selectedItem.ToString();
                    SearchSubtitleCommands.Instance.SearchSubtitleCommand.ExecuteIfCan(objects);
                }
                else
                {
                    if (!SearchSubtitleCommands.Instance.LastSearchName.Equals(selectedItem.ToString()))
                    {
                        SearchSubtitleCommands.Instance.LastSearchName = selectedItem.ToString();
                        SearchSubtitleCommands.Instance.SearchSubtitleCommand.ExecuteIfCan(objects);
                    }
                }
                GetSearchNameComboBox().SelectedIndex = 0;
            }
        }

        

        public System.Windows.Controls.ComboBox GetVideoComboBox()
        {
            return VideoComboBox;
        }
        public System.Windows.Controls.ComboBox GetNameComboBox()
        {
            return NameComboBox;
        }
        public System.Windows.Controls.TextBox GetSearchTextBox()
        {
            return SearchTextBox;
        }
        public System.Windows.Controls.ComboBox GetSearchNameComboBox()
        {
            return SearchNameComboBox;
        }

    }
}
